import { userLogin, queryUserMenus } from '@/api/login'
import { setCookie, getCookie } from '@/plugins/tools'
const user = {
  state: {
    token: getCookie('Access-Token') || '',
    menus: []
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_MENUS: (state, list) => {
      state.menus = list
    }
  },
  actions: {
    userLogin ({ commit, dispatch }, { username, password, verificationCode }) {
      return new Promise((resolve) => {
        userLogin({ username, password, verificationCode }).then(res => {
          if (res.data.code === 200) {
            const { token } = res.data.data
            commit('SET_TOKEN', token)
            setCookie('Access-Token', token, 7) // cookie有效期7天
            resolve()
          }
        })
      })
    },
    getUserRouterRoles ({ commit }) {
      return new Promise((resolve) => {
        queryUserMenus().then(res => {
          if (res.data.code === 200) {
            const roles = res.data.data
            const menuList = roles.map((item) => {
              const route = {
                name: item.url,
                path: '/' + item.url,
                params: {},
                meta: {
                  title: item.name.split('|')[0]
                }
              }
              if (Object.hasOwnProperty.call(item, 'list')) {
                route.children = item.list.map((childItem) => {
                  const childRoute = {
                    name: childItem.url,
                    path: childItem.url,
                    params: {},
                    meta: {
                      title: childItem.name.split('|')[0]
                    }
                  }
                  return childRoute
                })
              }
              return route
            })
            commit('SET_MENUS', menuList)
            resolve(menuList)
          }
        })
      })
    }
  }
}

export default user
